﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.ServiceProcess;
using System.Text;

namespace GetSeedWindowsService
{
    public partial class GetSeed : ServiceBase
    {
        private Process seedProcess = null;
        public GetSeed()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            WriteLog("p2p seed Service Start");
            StartLoadSeed();
        }

        protected override void OnStop()
        {
            KillProcessAndChildren(seedProcess.Id);
            WriteLog("p2p seed  Service Stop\n");

        }

        private void StartLoadSeed(Object sender = null, EventArgs e = null)
        {
            WriteLog("p2p seed   service start ");
            //ProcessStart("baseDir\\search\\elasticsearch\\bin", "elasticsearch-start.bat");
            WriteLog(AppDomain.CurrentDomain.BaseDirectory + "\\seed.bat");
            seedProcess = new Process();
            seedProcess.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
            seedProcess.StartInfo.CreateNoWindow = true;
            seedProcess.StartInfo.FileName = "cmd.exe";
            seedProcess.StartInfo.UseShellExecute = false;
            seedProcess.StartInfo.RedirectStandardError = true;
            seedProcess.StartInfo.RedirectStandardInput = true;
            seedProcess.StartInfo.RedirectStandardOutput = true;
            seedProcess.Start();
            // proc.StandardInput.WriteLine( "cd " + AppDomain.CurrentDomain.BaseDirectory);
            WriteLog("cd " + AppDomain.CurrentDomain.BaseDirectory, true);
            seedProcess.StandardInput.WriteLine("seed.bat  ");
            seedProcess.StandardInput.WriteLine("exit");
            while (!seedProcess.StandardOutput.EndOfStream)
            {
                string line = seedProcess.StandardOutput.ReadLine();
                WriteLog(line, true);
            }
            WriteLog("p2p seed  service end ");
        }

        private static void KillProcessAndChildren(int pid)
        {
            using (var searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid))
            {
                var managementObjects = searcher.Get();

                foreach (var obj in managementObjects)
                {
                    var managementObject = (ManagementObject)obj;
                    KillProcessAndChildren(Convert.ToInt32(managementObject["ProcessID"]));
                }
                try
                {
                    var proc = Process.GetProcessById(pid);
                    proc.Kill();
                }
                catch (ArgumentException)
                {
                    // Process already exited.
                }
            }
        }

        private void WriteLog(string logStr, bool wTime = true)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\seedService.log", true))
            {
                string timeStr = wTime == true ? DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ") : "";
                sw.WriteLine(timeStr + logStr);
            }
        }
    }
}
